<template>
  <div style="width: 100%">
    <slot name="dialogSlot">
      <el-input
        v-model="inputValue"
        class="input-with-select"
        clearable
        :disabled="disabledSel"
        placeholder="请选择"
        readonly
        @clear="clearInput"
      >
        <template #suffix>
          <vab-icon icon="close-circle-line" @click="clearInput" />
        </template>
        <template #append>
          <el-button :icon="Search" @click="handleShow" />
        </template>
      </el-input>
    </slot>
  </div>
  <vab-dialog
    v-model="dialogFormVisible"
    :append-to-body="appendToBodyVal"
    :before-close="handleClose"
    :close-on-click-modal="true"
    show-fullscreen
    :title="titleRef"
    :width="width"
  >
    <div>
      <vxe-table
        ref="xTable"
        v-model="selectValue"
        :auto-resize="true"
        :checkbox-config="{
          labelField: 'nodename',
          highlight: true,
          checkRowKeys: checkRowKeys,
          checkStrictly: checkStrictly
        }"
        :data="tableData"
        :height="refTableHeight"
        :row-config="{ keyField: 'id' }"
        :show-header="false"
        show-overflow
        :tree-config="{
          transform: true,
          rowField: 'id',
          parentField: 'parentid',
          expandRowKeys: expandRowKeys
        }"
        @checkbox-change="handleCheckboxChange"
      >
        <vxe-column tree-node type="checkbox" />
      </vxe-table>
    </div>
    <template #footer>
      <div style="position: relative; padding-right: 15px; text-align: right">
        <el-button :loading="loading" type="success" @click="handleConfirm"> 确认 </el-button>
        <el-button type="info" @click="handleClose">关闭</el-button>
      </div>
    </template>
  </vab-dialog>
</template>

<script>
import VabDialog from "@/plugins/VabDialog/index.vue";
import { Search } from "@element-plus/icons-vue";
import { postRequest } from "@/api/mains";
import { backTableHeight } from "@/api/mains";

export default {
  name: "DialogTreeMany",
  components: { VabDialog },
  props: {
    modelValue: {
      type: Array,
      default: () => {
        return [];
      }
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "请选择"
    },
    data: {
      type: Array,
      default: () => {
        return [];
      }
    },
    url: {
      type: String,
      default: () => {
        return "";
      }
    },
    tableHeight: {
      type: Number,
      default: 400
    },
    placeholder: {
      type: String,
      default: () => {
        return "请选择";
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: "50%"
    },
    checkStrictly: {
      type: Boolean,
      default: () => {
        return true;
      }
    }
  },
  emits: { "update:model-value": null },
  setup(props, { emit }) {
    const disabledSel = ref(props.disabled);

    const selectValue = ref(props.modelValue);
    const titleRef = ref(props.title);
    const dialogFormVisible = ref();
    const loading = ref(false);
    const inputValue = ref();

    const tableData = ref([]);
    const allData = ref([]);
    const expandRowKeys = ref([]); //默认展开的行
    const checkRowKeys = ref([]); //默认勾选的行
    const xTable = ref();
    const queryForm = ref({ EQ_ss: "1" });

    const actualMaxHeight = (props.tableHeight && props.tableHeight.value) || backTableHeight() + 10;
    const refTableHeight = ref(actualMaxHeight);

    const appendToBodyVal = ref(props.appendToBody);

    const handleShow = () => {
      if (!disabledSel.value) {
        dialogFormVisible.value = true;

        const newVal = props.modelValue;
        inputValue.value = "";
        const treeNodeNames = [];
        checkRowKeys.value = [];
        if (xTable.value != null && typeof xTable.value != "undefined") {
          xTable.value.setAllCheckboxRow(false); //取消勾选
        }
        allData.value.forEach(item => {
          if (xTable.value != null && typeof xTable.value != "undefined") {
            xTable.value.setCheckboxRow(item, false);
          }
          if (newVal != null && newVal.length > 0) {
            const selArr = newVal;
            checkRowKeys.value = selArr;
            for (let i = 0; i < selArr.length; i++) {
              if (selArr[i] == item.id) {
                treeNodeNames.push(item.nodename);
                //checkRowKeys.value.push(selArr[i])//只能初始化一次
                if (xTable.value != null && typeof xTable.value != "undefined") {
                  xTable.value.setCheckboxRow(item, true);
                }
              }
            }
          }
        });
        inputValue.value = treeNodeNames.join();
      }
    };
    const handleClose = () => {
      dialogFormVisible.value = false;
    };

    const clearInput = () => {
      if (!disabledSel.value) {
        emit("update:model-value", "");
      }
    };
    const handleConfirm = () => {
      //emit('callbackselect')

      const rows = xTable.value.getCheckboxRecords(true);
      //const $pulldown2 = xDown.value
      inputValue.value = rows.map(item => item.nodename).join();
      emit(
        "update:model-value",
        rows.map(item => item.id)
      );

      handleClose();
    };
    const handleCheckboxChange = () => {
      /* const rows = xTable.value.getCheckboxRecords(true)
        //const $pulldown2 = xDown.value
        inputValue.value = rows.map((item) => item.nodename).join()
        emit(
          'update:model-value',
          rows.map((item) => item.id)
        ) */
      //emit('on-select-tree-many', rows)
      /*$pulldown2.hidePanel().then(() => {
      tableData.value = allData.value
    })*/
    };

    const handleFetchTreeData = async () => {
      if (props.url != null && typeof props.url != "undefined" && props.url != "") {
        const responseData = await postRequest(props.url, queryForm.value);
        tableData.value = responseData.data;
        allData.value = responseData.data;

        inputValue.value = "";
        const treeNodeNames = [];
        allData.value.forEach(item => {
          if (item.parentid == "root") {
            expandRowKeys.value.push(item.id);
          }
          if (selectValue != null && selectValue.value.length > 0) {
            checkRowKeys.value = selectValue.value;
            for (let i = 0; i < selectValue.value.length; i++) {
              if (selectValue.value[i] == item.id) {
                treeNodeNames.push(item.nodename);
                //checkRowKeys.value.push(selectValue.value[i])//只能初始化一次
                if (xTable.value != null && typeof xTable.value != "undefined") {
                  xTable.value.setCheckboxRow(item, true);
                }
              }
            }
          }
        });
        inputValue.value = treeNodeNames.join();
      }
    };

    watch(
      () => props.disabled,
      () => {
        disabledSel.value = props.disabled;
      }
    );

    watch(
      () => tableData,
      newVal => {
        tableData.value = newVal;
        allData.value = newVal;

        inputValue.value = "";
        const treeNodeNames = [];
        allData.value.forEach(item => {
          if (item.parentid == "root") {
            expandRowKeys.value.push(item.id);
          }
          if (selectValue != null && selectValue.value.length > 0) {
            checkRowKeys.value = selectValue.value;
            for (let i = 0; i < selectValue.value.length; i++) {
              if (selectValue.value[i] == item.id) {
                treeNodeNames.push(item.nodename);
                //checkRowKeys.value.push(selectValue.value[i])//只能初始化一次
                if (xTable.value != null && typeof xTable.value != "undefined") {
                  xTable.value.setCheckboxRow(item, true);
                }
              }
            }
          }
        });
        inputValue.value = treeNodeNames.join();
      }
    );

    watch(
      () => props.data,
      newVal => {
        tableData.value = newVal;
        allData.value = newVal;

        inputValue.value = "";
        const treeNodeNames = [];
        allData.value.forEach(item => {
          if (item.parentid == "root") {
            expandRowKeys.value.push(item.id);
          }
          if (selectValue != null && selectValue.value.length > 0) {
            checkRowKeys.value = selectValue.value;
            for (let i = 0; i < selectValue.value.length; i++) {
              if (selectValue.value[i] == item.id) {
                treeNodeNames.push(item.nodename);
                //checkRowKeys.value.push(selectValue.value[i])//只能初始化一次
                if (xTable.value != null && typeof xTable.value != "undefined") {
                  xTable.value.setCheckboxRow(item, true);
                }
              }
            }
          }
        });
        inputValue.value = treeNodeNames.join();
      }
    );

    watch(
      () => props.modelValue,
      newVal => {
        inputValue.value = "";
        const treeNodeNames = [];
        checkRowKeys.value = [];
        if (xTable.value != null && typeof xTable.value != "undefined") {
          xTable.value.setAllCheckboxRow(false); //取消勾选
        }
        allData.value.forEach(item => {
          if (xTable.value != null && typeof xTable.value != "undefined") {
            xTable.value.setCheckboxRow(item, false);
          }
          if (newVal != null && newVal.length > 0) {
            const selArr = newVal;
            checkRowKeys.value = selArr;
            for (let i = 0; i < selArr.length; i++) {
              if (selArr[i] == item.id) {
                treeNodeNames.push(item.nodename);
                //checkRowKeys.value.push(selArr[i])//只能初始化一次
                if (xTable.value != null && typeof xTable.value != "undefined") {
                  xTable.value.setCheckboxRow(item, true);
                }
              }
            }
          }
        });
        inputValue.value = treeNodeNames.join();
      }
    );

    onMounted(() => {
      handleFetchTreeData();
    });
    return {
      disabledSel,
      selectValue,
      titleRef,
      dialogFormVisible,
      loading,
      inputValue,
      tableData,
      allData,
      expandRowKeys,
      checkRowKeys,
      xTable,
      queryForm,
      refTableHeight,
      appendToBodyVal,
      handleShow,
      handleClose,
      clearInput,
      handleConfirm,
      handleCheckboxChange,
      handleFetchTreeData,
      Search
    };
  }
};
</script>

<style lang="scss" scoped>
.down-tree {
  width: 100%;
  height: 55vh;
  margin-top: 10px;
  overflow: auto;
}
:deep(.vxe-table--body) {
  .vxe-body--column {
    background-image: none;
  }
}
:deep(.vxe-table) {
  .vxe-table--border-line {
    border: none;
  }
}
:deep(.el-dialog) {
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0;
  }
}
</style>
